<?php
use think\Db;
// 团队积累
// 单字幕函数 +----------------------------------------------------------------------
/**
 * 打印变量,断点
 *
 * @param unknown $a 变量
 * @param string $b 是否打印变量类型
 */
function t($a, $b = false)
{
    echo "<pre>";
    if ($b) {
        var_dump($a);
    } else {
        print_r($a);
    }
    exit("</pre>");
}

/**
 * 页面输出
 *
 * @param string $msg
 *            信息
 * @param string $exit
 *            是否阻断
 */
function e($msg = '', $exit = false)
{
    if ($exit) {
        exit("------------------{$msg}-------------------<br>");
    } else {
        echo ("------------------{$msg}-------------------<br>");
    }
}

function l($key = '', $type = 'zh')
{
    return Db::name('lang')->where('type', $type)
        ->where('key', $key)
        ->value('val');
}

/**
 * 获取配置
 *
 * @param string $name
 *            配置一级键值的名称
 * @param string $key
 *            配置二级键值的名称
 * @return \think\mixed
 */
function c($name = '', $key = '')
{
    $rs = \think\Config::get($name);
    if ($key !== '') {
        return isset($rs[$key]) ? $rs[$key] : "";
    }
    return $rs;
}

/**
 * URL重定向
 *
 * @param string $url
 *            重定向的URL地址
 * @param integer $time
 *            重定向的等待时间（秒）
 * @param string $msg
 *            重定向前的提示信息
 * @return 跳转页面
 */
function r($url, $time = 0, $msg = '')
{
    if (empty($msg))
        $msg = "系统将在{$time}秒之后自动跳转到{$url}！";

    if (! headers_sent()) {
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo ($msg);
        }
    } else {
        $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0) {
            $str .= $msg;
        }
        echo ($str);
    }
    exit();
}
//输出图片
function pic($filename=''){
  $filename = $filename ? $filename : "/static/vendor/404.png";
  return $filename;
}

// 判断函数 +----------------------------------------------------------------------
function is_post()
{
    return request()->isPost();
}
// 匹配是否为UTF-8编码
function is_utf8($utf8str)
{
    if (preg_match('/^([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){1}/', $utf8str) == true || preg_match('/([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){1}$/', $utf8str) == true || preg_match('/([' . chr(228) . '-' . chr(233) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}[' . chr(128) . '-' . chr(191) . ']{1}){2,}/', $utf8str) == true) {
        return true;
    } else {
        return false;
    }
}
//获取post
function post($key = '', $default = null, $filter = ''){
    $rs = request()->post($key, $default, $filter);
    if(isset($rs['file'])) unset($rs['file']);
    return $rs;
}
// js跳转页面
function js_url($url = '', $second=1)
{
    $s = bcmul($second, 1000);
    if ($url) {
        exit("<script>setTimeout(function(){window.location.href='" . $url . "';},".$s.");</script>");
    } else {
        exit("<script>setTimeout('window.location.reload();',".$s.");</script>");
    }
}
// 附件
function attach($path, $file = false, $type = "")
{
    if (in_array($type, ['small','middle'])) {
        $path = dirname($path) . "/" . $type . "_" . basename($path);
        if (! is_file(APP_PATH . "../public/" . $file)) {
            $path = dirname($path) . "/" . basename($path);
        }
    }
    if ($file) {
        return APP_PATH . "../public/" . $path;
    }
    return $path ? "/" . $path : "";
}
/**
 * 参数随机字符串
 * @param number $length 长度， 最大为62位
 * @return string
 */
function rand_str( $length = 10 ){
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
    $strlen = 62;
    while($length > $strlen){
        $str .= $str;
        $strlen += 62;
    }
    $str = str_shuffle($str);
    return substr($str,0,$length);
}

// 通用函数 +----------------------------------------------------------------------
/**
 * 获取sql
 */
function com_sql()
{
    $sql = \think\Db::getLastSql();
    t($sql);
}

/**
 * 统计日志
 *
 * @param unknown $data
 *            统计的日志数据
 * @param string $name
 *            日志文件名
 */
function com_log($data = [], $name = 'log')
{
    if (is_string($data))
        $data = [
            'default' => $data
        ];
    $str = "\r\n-----------------------------------------" . date("Y-m-d H:i:s") . "-----------------------------------------\r\n";
    foreach ($data as $key => $val) {
        $val = is_string($val) ? $val : json_encode($val);
        $str .= "$key:$val\r\n";
    }
    $dir = __DIR__ . "/../public/uploads/logs/" . date("Ym") . "/";
    com_mkdir($dir);
    $file = "$name" . date("Ymd") . ".txt";
    file_put_contents($dir . $file, $str, FILE_APPEND);
}

/**
 * 新建csv
 *
 * @param unknown $data
 *            数据库搜索出来的数据
 * @param unknown $title
 *            txt表头
 * @param unknown $field
 *            表头对应的字段
 * @param unknown $pre
 *            文件名前缀
 * @param unknown $type
 *            文件类型 csv/txt
 * @return string
 */
function com_down_csv($data, $title = [], $field = [], $pre = '', $type = 'csv')
{

    switch ($type) {
        case 'xls':
            $tag = "\t";
            break;
        default:
            $tag = ",";
            break;
    }
    $content = "";
    // 标题
    foreach ($title as $val) {
        $content .= $val . "{$tag}";
    }
    $content = rtrim($content, "{$tag}") . "\r\n";

    // 内容
    foreach ($data as $val) {
        foreach ($field as $f) {
            $temp_f = str_replace(array("{$tag}"), array(""), $val[$f]);
            $content .= $temp_f . "{$tag}";
        }
        $content = rtrim($content, "{$tag}") . "\r\n";
    }
    $dir = c('a.uploads') . "{$type}}/" . date("Y-m") . "/" . date("d");
    com_mkdir($dir);
    $filename = $dir . "/" . $pre . "_" . time() . "." . $type;
    file_put_contents($filename, iconv('UTF-8',"GB2312//IGNORE",$content));
    return "http://" . $_SERVER['HTTP_HOST'] . "/" . $filename;
}

/**
 * 重置url
 *
 * @param unknown $url
 *            原始的url
 * @param unknown $param
 *            需添加的参数数组
 * @param string $is_urlencode
 *            是否转义
 * @return string
 */
function com_build_url($url, $param = [], $is_urlencode = false)
{
    $arr = explode("?",$url);
    $base = $arr[0];

    //重置参数
    if(isset($arr[1])){
        $temp = explode("&",$arr[1]);
        $tmp = [];
        foreach($temp as $v){
            $t = explode("=",$v);
            $tmp[$t[0]] = $t[1];
        }
        $param = array_merge($tmp,$param);
    }
    $p = "?";
    foreach($param as $k => $v){
        if(empty($v)) continue;
        $v = urldecode($v);
        $k = urldecode($k);
        $p .=urlencode($k)."=".urlencode($v)."&";
    }
    $p = rtrim($p,"&");
    return $base.$p;
}

/**
 * 验证类型
 *
 * @param string $url
 *            链接地址
 * @param unknown $ext
 *            后缀类型
 */
function com_check_type($url = '', $ext = ['gif','jpeg','jpg','png','bmp'])
{
    $arr = explode('.', $url);
    $e = end($arr);
    return in_array($e, $ext);
}

/**
 * 取得图片绝对路径
 *
 * @param string $path
 *            图片相对路径
 * @param string $type
 *            图片类型 small/middle
 * @param string $check
 *            是否返回404图片
 * @return 返回图片绝对路径
 */
function com_get_pic($path = '', $type = '', $check = false, $is_domain = false)
{
    $domain = $is_domain ? "http://{$_SERVER['HTTP_HOST']}/" : "";
    if (empty($path)) {
        return $check ? "./static/404.png" : '';
    }

    $file = $path;
    if (in_array($type, array(
        'small',
        'middle'
    ))) {
        $file = dirname($path) . "/" . $type . "_" . basename($path);
        if (! is_file(APP_PATH . "../public/" . $file)) {
            $file = dirname($path) . "/" . basename($path);
        }
    }
    if ($check && ! is_file(APP_PATH . "../public/" . $file)) {
        $file = "./static/404.png";
    }
    return $domain . $file;
}

/**
 * 远程采集图片到临时文件
 *
 * @param string $url
 *            采集的地址
 * @param string $filename
 *            采集之后的名称， 不填写则为时间戳
 * @return string|\my\false;
 */
function com_fetch_pic($url = '', $filename = "")
{
    if (! $url)
        return '';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    $data = curl_exec($ch);
    if (curl_errno($ch) !== 0) {
        return com_error([
            'curl错误' . curl_errno($ch)
        ]);
    }
    curl_close($ch);
    $ext = strrchr($url, ",");
    $ext = in_array($ext, [
        '.gif',
        '.jpg',
        '.bmp'
    ]) ? $ext : ".jpg";
    $filename = $filename ? $filename : time() . rand(1000, 999) . $ext;
    $dir = c('a.uploads') . "temp/" . date("Ym") . "/" . date("d") . "/";
    com_mkdir($dir);
    $path = $dir . $filename;
    file_put_contents($path, $data);
    return $path;
}

/**
 * 获取文件大小
 *
 * @param unknown $file
 *            文件路径
 * @return string
 */
function com_get_filesize($file)
{
    $perms = stat($file);
    $size = $perms['size'];
    $a = [
        'B',
        'KB',
        'MB',
        'GB',
        'TB'
    ];
    $pos = 0;
    while ($size >= 1024) {
        $size /= 1024;
        $pos ++;
    }
    return round($size, 2) . $a[$pos];
}

/**
 * 获取文件修改时间
 *
 * @param unknown $file
 *            文件路径
 * @return string
 */
function com_get_filetime($file)
{
    return date("Y-m-d H:i:s", filemtime($file));
}


/**
 * 重写TP5验证，封装到前端
 *
 * @param unknown $rule
 *            规则
 * @param unknown $msg
 *            提示
 * @param unknown $data
 *            数据
 * @param boolean $exit
 *            是否输出到前端
 * @return boolean
 */
function com_validate($rule, $msg, $data, $exit = false)
{
    $v = new \think\Validate($rule, $msg);
    $v->batch();
    if ($v->check($data))
        return true;
    // 把错误捕捉到前端类里
    $err = $v->getError();
    $msg = current($err);
    com_error($msg,array_search($msg, $err));
    com_check();
}

/**
 * 密码
 *
 * @param string $password
 */
function com_password($password = '123456')
{
    $str = "abcdefghijklmnopqrstuvwxyz";
    return md5($password . $str);
}

/**
 * 上传单个图片//允许类型 'jpg', 'gif', 'png', 'jpeg','ico'
 *
 * @param string $dir
 *            目录
 * @param string $name
 *            上传字段名称
 * @param string $is_thumb
 *            是否生成缩略图
 * @param unknown $con_thumb
 *            缩略图大小配置
 * @return 返回路径
 */
function com_up_pic($dir = 'article', $is_thumb = true, $con_thumb = ['small'=>[100,100], 'middle'=>[300,300]])
{
    return \my\Up::upPic($dir, $is_thumb, $con_thumb);
}

/**
 * 上传文件
 *
 * @param string $dir
 *            上传到目录
 * @param string $name
 *            上传文件字段
 * @param unknown $exts
 *            允许文件的后缀名
 * @return 返回路径
 */
function com_up_file($dir = 'rsa', $name = 'pic', $exts = [])
{
    return \my\Up::upFile($dir, $name, $exts);
}

/**
 * 解压文件到指定目录
 *
 * @param
 *            string zip压缩文件的路径
 * @param
 *            string 解压文件的目的路径
 * @param
 *            boolean 是否以压缩文件的名字创建目标文件夹
 * @param
 *            boolean 是否重写已经存在的文件
 * @return boolean 返回成功 或失败
 */
function com_unzip($src_file, $dest_dir = false, $create_zip_name_dir = true, $overwrite = true)
{
    $zip = zip_open($src_file);
    if (! $zip)
        return false;

    $splitter = ($create_zip_name_dir === true) ? "." : "/";
    if ($dest_dir === false)
        $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter)) . "/";
    com_mkdir($dest_dir);

    while ($zip_entry = zip_read($zip)) {
        if (! zip_entry_open($zip, $zip_entry, "r"))
            continue;

        $file_name = $dest_dir . zip_entry_name($zip_entry);
        if ($overwrite === true || $overwrite === false && ! is_file($file_name)) {

            if (substr($file_name, - 1) == '/') {
                com_mkdir($file_name);
            } else {
                $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                file_put_contents($file_name, $fstream);
            }
            chmod($file_name, 0777);
            echo "save: " . $file_name . "<br />";
        }
        zip_entry_close($zip_entry);
    }
    zip_close($zip);
    return true;
}

/**
 * 递归创建目录
 *
 * @param unknown $dir
 *            文件路径
 * @return true or false
 */
function com_mkdir($dir)
{
    if (is_dir($dir) || @mkdir($dir))
        return true;
    if (! com_mkdir(dirname($dir)))
        return false;
    return @mkdir($dir, 0777);
}

/**
 * 下载excle
 *
 * @param unknown $data
 *            内容
 * @param unknown $title
 *            标题
 * @param unknown $field
 *            内容的过滤字段
 * @param unknown $type
 *            文件位置/文件名
 * @return 返回文件的绝对路径
 */
function com_csv($data, $title = [], $field = [], $type)
{
    $content = "";
    // 标题
    foreach ($title as $val) {
        $content .= $val . ",";
    }
    $content = rtrim($content, ",") . "\r\n";
    // 内容
    foreach ($data as $val) {
        foreach ($field as $f) {
            $temp_f = str_replace(array(","), array(""), $val[$f]);
            if(in_array($f, ["bank_no","order_no","phone"])){
                $temp_f = "'".$temp_f;
            }
            $content .= "\"".$temp_f . "\",";
        }
        $content = rtrim($content, ",") . "\r\n";
    }
    $dir = c('a.uploads') . "csv/" . date("Y-m") . "/" . date("d");
    com_mkdir($dir);
    $filename = $dir . "/" . $type . "_" . time() . ".csv";
    file_put_contents($filename, mb_convert_encoding($content,"gbk","utf-8"));
    return "http://" . $_SERVER['HTTP_HOST'] . "/" . $filename;
}

/**
 * 截取utf8字符串,完美支持中文
 *
 * @param
 *            : 待截取的字符串,从第几个字符开始截取，截取长度，如超过长度是否加“..”
 * @param string $str
 *            截取的字符串
 * @param int $len
 *            截取长度
 * @param int $from
 *            从那个位置开始截取
 * @param string $adddot
 *            截取后用什么填充 默认...
 */
function com_substr($str, $len, $adddot = '...', $from = 0)
{
    if ($adddot && mb_strlen($str, 'utf-8') > intval($len)) {
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $from . '}' . '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $len . '}).*#s', '$1', $str) . $adddot;
    } else {
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $from . '}' . '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $len . '}).*#s', '$1', $str);
    }
}

/**
 * 返回ip地址或IPV4数字
 *
 * @param number $type
 *            0返回ip， 1返回数字
 * @return ip地址
 */
function com_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = ip2long($ip);
    $ip = $long ? array(
        $ip,
        $long
    ) : array(
        '0.0.0.0',
        0
    );
    return $ip[$type];
}

/**
 * 返回服务器ip
 */
function com_server_ip()
{
    return gethostbyname($_SERVER["SERVER_NAME"]);
}

/**
 * 产生token值
 *
 * @param string $user_id
 *            用户id, 或者其他
 */
function com_token($user_id = '')
{
    $str = time() . rand(100, 999) . $user_id;
    return md5($str);
}

/**
 * 生成订单号
 *
 * @return string
 */
function com_order_no($pre = '')
{
    $id = Db::name('temp_id')->insertGetId([
        't' => 1
    ]);
    return $pre . date('Ymd') . (100000000 + $id);
}

//错误信息
function com_error($msg='操作失败!',$name='nokey')
{
    return \my\Front::error($msg, $name);
}
//输出返回
function com_check($config = [])
{
    return \my\Front::check($config);
}

/**
 * 获取模块名称
 */
function com_module()
{
    $request = \think\Request::instance();
    return strtolower($request->module());
}

/**
 * 获取控制器名称
 */
function com_controller()
{
    $request = \think\Request::instance();
    return strtolower($request->controller());
}

/**
 * 获取动作名称
 */
function com_action()
{
    $request = \think\Request::instance();
    return strtolower($request->action());
}

/**
 * 取得前台登陆用户信息
 *
 * @param string $field
 *            字段
 */
function com_userinfo($field = '')
{
    return \my\G::get($field);
}

/* ============ */
/**
 * 格式化显示时间
 *
 * @param unknown $time
 *            时间
 * @param string $format
 *            格式
 * @return string
 */
function com_formate_time($time, $format = "Y-m-d H:i")
{
    return $time ? date($format, $time) : "";
}

/**
 * 格式化多选删除选项框
 *
 * @param unknown $id
 *            主键id值
 * @return string
 */
function com_format_checkbox($id)
{
    return "<input type='checkbox' name='id[]' tid='{$id}'>";
}

/**
 * 截取中间字符 /1**1/
 * @param [type] $str
 */
function com_strlen( $str,$front=3,$back=4 ){

    $str=(string)$str;
    $strlen     = mb_strlen($str, 'utf-8');
    if($strlen<=($front+$back)) return $str;

    $midstr="";
    for($i=0;$i<$strlen-$front-$back;$i++)
    {
        $midstr.="*";
    }

    return mb_substr($str, 0, $front, 'utf-8').$midstr.mb_substr($str, -$back,$back, 'utf-8');
}

// 是否是手机
function ismobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

        // 此条摘自TPM智能切换模板引擎，适合TPM开发
    if (isset($_SERVER['HTTP_CLIENT']) && 'PhoneClient' == $_SERVER['HTTP_CLIENT'])
        return true;
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA']))
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        // 判断手机发送的客户端标志,兼容性有待提高
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
/*
计算当前页码
:param cur_page: 当前页码
:param page_count: 总页码
:return:
*/
function com_cur_page($cur_page,$page_count){
    $cur_page = $cur_page<=$page_count ? $cur_page : $page_count;
    $cur_page = $cur_page>1 ? $cur_page : 1;
    return $cur_page;
}

/*
计算分页数据
:param item_count:
:param cur_page:
:param page_size:
:return:
*/
function com_page_data($item_count, $cur_page, $page_size){
    $page_count = ceil($item_count/$page_size);
    $temp = [
        'list'=>[],#数字目录
        'first'=>'',
        'last'=>'',
        'pre'=> '',
        'next'=> '',
        'cur_page'=> $cur_page, #当前页
        'item_count'=> $item_count,#总条数
        'page_count'=> $page_count, #总页数
    ];
    if($item_count==0) return $temp;

    #数字目录
    if($cur_page < 7){
        $start = 1;
        $end = $page_count<=6 ? $page_count : 7;
    }elseif($cur_page>=7 and $cur_page<$page_count-5){
      $start = $cur_page-4;
      $end = $cur_page+4;
    }elseif($cur_page>$page_count-7){
      $start = $page_count-7;
      $end = $page_count;
    }
    for($i=$start;$i<$end+1;$i++){
      $temp['list'][] = $i;
    }
    #快捷页码
    $temp['first'] = $start>1?1:'';
    $temp['last'] = $end<$page_count? $page_count : '';
    $temp['pre'] = $cur_page>1 ? $cur_page-1 : '';
    $temp['next'] =  $cur_page<$page_count ? $cur_page+1 : '';
    return $temp;
}
//后台列表分页生成
function com_list_page($sql,$param,$cur_page=1,$page_size=12,$tmp='list',$re='html'){
    $cur_page = (int)$cur_page;
    $sql_count = str_replace('[1]','count(*) as num',$sql);
    $res = Db::query($sql_count,$param);
    $res = $res[0];
    $item_count = $res['num'];

    $page_count = ceil($item_count/$page_size);
    $cur_page = com_cur_page($cur_page,$page_count);

    $page_data = com_page_data($item_count,$cur_page,$page_size);
    if($re == 'data')
        return $page_data;
    $html = "<div class='layui-box layui-laypage layui-laypage-default'>";
    #首页
    if ($page_data['first'])
        $html .= "<a  href='javascript:search(\"{$tmp}\",{$page_data['first']})' class='layui-laypage-prev'>首页</a>";
    #上一页
    if ($page_data['pre']){
        $html .= "<a  href='javascript:search(\"{$tmp}\",{$page_data['pre']})' class='layui-laypage-prev'>上一页</a>";
    }else{
        $html .= "<a  href='javascript:;' class='layui-laypage-prev layui-disabled'>上一页</a>";
    }
    #目录
    foreach ($page_data['list'] as $p) {
      if($p==$cur_page){
          $html .= "
          <span class='layui-laypage-curr'>
              <em class='layui-laypage-em'></em>
              <em class='current'>{$p}</em>
          </span>
          ";
      }else{
        $html .= "<a href='javascript:search(\"{$tmp}\",{$p})'>{$p}</a>";
      }
    }

    #下一页
    if($page_data['next']){
        $html .= "<a  href='javascript:search(\"{$tmp}\",{$page_data['next']})' class='layui-laypage-next'>下一页</a>";
    }else{
        $html .= "<a  href='javascript:;' class='layui-laypage-next layui-disabled'>下一页</a>";
    }
    #尾页
    if($page_data['last'])
        $html .= "<a  href='javascript:search(\"{$tmp}\",{$page_data['last']})' class='layui-laypage-next'>尾页</a>";

    $html .="</div>";
    if($re == 'html')
        return $html;

    return ['html'=>$html,'data'=>$page_data];
}
//列表数据
function com_list_body($list, $param){

    if(count($list)==0)
        return "<tr><td colspan=".count($param)."><h1>没有数据</h1></td></tr>";

    $tbody = "";
    foreach ($list as $v) {
      $tbody .= "<tr>";
      foreach($param as $val){
        $tbody .= "<td>{$v[$val]}</td>";
      }
      $tbody .= "</tr>";
    }
    return $tbody;
}
//统计数据
function com_list_count($sql, $param,$d){
    $tip = [];
    foreach($d as $v){
        if(strpos($sql,'where')){
            $sql2 = $sql.$v[2];
        }else{
            if($v[2]){
                $sql2 = $sql." where ". ltrim(ltrim($v[2]),"and");
            }else{
                $sql2 = $sql;
            }
        }
      $rs = Db::query(str_replace("[1]", $v[1], $sql2),$param);
      $tip[$v[0]] = com_number($rs[0]['nums']);
    }

    $keys = array_keys($tip);
    $tbody  = '<table class="layui-table"><thead><tr>';
    foreach($keys as $val){
        $tbody .= "<th>{$val}</th>";
    }
    $tbody .= '</tr></thead><tbody><tr class="success">';
    foreach($tip as $val){
        $tbody .= "<th>{$val}</th>";
    }
    $tbody .= '</tr></tbody></table>';
    return $tbody;
}
#勾选
function com_checkbox($id){
    return '<input type="checkbox" name="id[]" tid="'.$id.'">';
}

# 排序
function com_sort($table, $id, $val){
    return '<div class="layui-input-inline" style="width:100px;"><input type="text" onchange="com_sort(this)" table="'.$table.'" tid="'.$id.'" value="'.$val.'" class="layui-input"></div>';
}

#拷贝按钮
function com_copy($table,$id){
        $js = "
            layui.layer.confirm(\"您确定要拷贝该条数据吗?\",{\"icon\":3},function(){
              $.ajax({
                    url: \"\/api\/copys\/table\/{$table}\/id\/{$id}\",
                    dataType: \"json\",
                    success: function(rs) {
                        _action(rs);
                    },
                    error:function(){
                        layer.msg(\"服务器开小差!\");
                    }
                });
            });
        ";
        $a = "<a class='layui-btn layui-btn-mini layui-btn-warm' href='javascript:{$js}'>拷贝</a>";
        return $a;
}
//编辑按钮
function com_btn_edit($url='/',$width='',$height='',$title='编辑'){
    if($width and $height and !ismobile()){
      $a = "<a class='layui-btn layui-btn-mini layui-btn-normal' href='javascript:layer.open({
            type: 2,
            title: \"{$title}\",
            area: [\"{$width}\", \"{$height}\"],
            content: \"{$url}\"
          })'>{$title}</a>";
    }else{
      $a = "<a class='layui-btn layui-btn-mini layui-btn-normal' href='javascript:layer.open({
        type: 2,
        title: \"{$title}\",
        area: [\"100%\", \"100%\"],
        content: \"{$url}\"
      })'>{$title}</a>";
    }
    return $a;
}
//删除按钮
function com_btn_del($url='/',$msg='您确定要删除?',$title='删除'){
    $js = "
        layui.layer.confirm(\"{$msg}\",{\"icon\":3},function(){
          $.ajax({
                url: \"{$url}\",
                dataType: \"json\",
                success: function(rs) {
                    _action(rs);
                },
                error:function(){
                    layer.msg(\"服务器开小差!\");
                }
            });
        });
    ";
    $a = "<a class='layui-btn layui-btn-mini layui-btn-danger' href='javascript:{$js}'>{$title}</a>";
    return $a;
}
//确认按钮
function com_btn_confirm($url='/',$msg='您确定要通过?',$title='通过'){
    $js = "
        layui.layer.confirm(\"{$msg}\",{\"icon\":3},function(){
          $.ajax({
                url: \"{$url}\",
                dataType: \"json\",
                success: function(rs) {
                    _action(rs);
                },
                error:function(){
                    layer.msg(\"服务器开小差!\");
                }
            });
        });
    ";
    $a = "<a class='layui-btn layui-btn-mini layui-btn-normal' href='javascript:{$js}'>{$title}</a>";
    return $a;
}

function com_number($num="100",$pos=4,$conv=true)
{
    if(!is_numeric($num)) return 0;
    $str= sprintf("%.".$pos."f",substr(sprintf("%.".($pos+2)."f", $num), 0, -2));
    return $conv?(float)$str:$str;
}
